var express = require('express');
var xmlparser = require('express-xml-bodyparser');
var crypto = require('crypto');
var router = express.Router();
var token = "gumpyang";

/* GET home page. */
router.get('/node', function(req, res, next) {
	var signature = req.query.signature;
	var timestamp = req.query.timestamp;
	var nonce = req.query.nonce;
	var echostr = req.query.echostr;
	/*  加密/校验流程如下： */
	//1. 将token、timestamp、nonce三个参数进行字典序排序
	var array = new Array(token,timestamp,nonce);
	array.sort();
	var str = array.toString().replace(/,/g,"");
	//2. 将三个参数字符串拼接成一个字符串进行sha1加密
	var sha1Code = crypto.createHash("sha1");
	var code = sha1Code.update(str,'utf-8').digest("hex");
	//3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	if(code===signature){
		console.log("gump get test:" + str);
		res.send(echostr)
	}else{
		console.log("gump get test error");
		res.send("error");
	}
});

/* POST home page. */
router.post('/node', xmlparser({trim:false, explicitArray:false}), function(req, res, next) {
	var signature = req.query.signature;
	var timestamp = req.query.timestamp;
	var nonce = req.query.nonce;
	var echostr = req.query.echostr;
	/*  加密/校验流程如下： */
	//1. 将token、timestamp、nonce三个参数进行字典序排序
	var array = new Array(token,timestamp,nonce);
	array.sort();
	var str = array.toString().replace(/,/g,"");
	//2. 将三个参数字符串拼接成一个字符串进行sha1加密
	var sha1Code = crypto.createHash("sha1");
	var code = sha1Code.update(str,'utf-8').digest("hex");
	//3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
	if(code===signature){
		console.log("gump post test:" + str);
		console.log("gump post body:" + JSON.stringify(req.body));
		var tousername = req.body.xml.fromusername;
	 	var data = '<xml><ToUserName>' + tousername + '</ToUserName></xml>';
		echostr += data;
		console.log("echostr " + echostr);
		// res.send(data);
		res.writeHead(200, {'Content-Type': 'application/xml'});
		res.end(data);
	}else{
		console.log("gump post test error");
		res.send("error");
	}
});

module.exports = router;
